<template>
    <view class="bg-gray-50">
        <!-- 医院信息区域 -->

        <Care />

        <!-- 常规项目区域 -->
        <view class="bg-white mx-4 mt-4 rounded-3xl p-6 shadow-sm">
            <view class="flex items-center justify-between">
                <text class="text-[40rpx] font-semibold text-gray-800">常规项目</text>
                <view class="flex items-center text-gray-500 text-[32rpx]" @click="toggleCustom">
                    <text>{{ isCustomExpanded ? '收起' : '展开' }}</text>
                    <IconFont :name="isCustomExpanded ? 'arrow-up' : 'arrow-down'" size="12" class="ml-2" />
                </view>
            </view>

            <!-- 动态健康项目 -->
            <view v-show="isCustomExpanded" class="mt-6">
                <!-- 加载状态 -->
                <view v-if="loading" class="flex items-center justify-center py-8">
                    <text class="text-gray-500">加载中...</text>
                </view>
                
                <!-- 健康数据列表 -->
                <view v-else-if="healthData.length > 0" class="space-y-3">
                    <view 
                        v-for="item in healthData" 
                        :key="item.id"
                        class="bg-white rounded-xl p-4 shadow-sm border border-gray-50 hover:shadow-md transition-shadow duration-200"
                    >
                        <view class="flex items-center">
                            <!-- 图标区域 -->
                            <view class="relative">
                                <view class="w-12 h-12 rounded-xl flex items-center justify-center mr-4"
                                    :class="getHealthStatus(item.subName, item.subRes).bgColor || 'bg-gradient-to-br from-green-400 to-green-500'">
                                    <IconFont :name="getIconByName(item.subName)" size="20" color="white" />
                                </view>
                                <!-- 状态指示点 -->
                                <view class="absolute -top-1 -right-1 w-4 h-4 rounded-full border-2 border-white"
                                    :class="getHealthStatus(item.subName, item.subRes).dotColor || 'bg-green-400'">
                                </view>
                            </view>
                            
                            <!-- 内容区域 -->
                            <view class="flex-1 min-w-0">
                                <view class="flex items-center justify-between mb-2">
                                    <text class="text-[40rpx] font-semibold text-gray-800 truncate">{{ item.subName }}</text>
                                    <view 
                                        class="px-3 py-1 rounded-full text-[24rpx] font-medium shadow-sm"
                                        :class="getHealthStatus(item.subName, item.subRes).color"
                                    >
                                        {{ getHealthStatus(item.subName, item.subRes).status }}
                                    </view>
                                </view>
                                <view class="text-[32rpx] text-gray-600 mb-3">
                                    {{ formatDisplayValue(item.subName, item.subRes, item.updateTime) }}
                                </view>
                                
                                <!-- 操作按钮 -->
                                <view class="flex items-center space-x-2">
                                    <view 
                                        class="flex items-center px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors duration-200"
                                        @click="editHealthRecord(item)"
                                    >
                                        <IconFont name="edit" size="14" color="#3b82f6" />
                                        <text class="text-[24rpx] text-blue-600 ml-1">编辑</text>
                                    </view>
                                    <view 
                                        class="flex items-center px-3 py-1.5 rounded-lg bg-red-50 hover:bg-red-100 transition-colors duration-200"
                                        @click="deleteHealthRecord(item.id)"
                                    >
                                        <IconFont name="close" size="14" color="#ef4444" />
                                        <text class="text-[24rpx] text-red-600 ml-1">删除</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 空状态 -->
                <view v-else class="flex items-center justify-center py-8">
                    <text class="text-gray-500">暂无健康数据</text>
                </view>
            </view>
        </view>
    </view>

    <!-- 编辑弹窗 -->
    <nut-popup v-model:visible="showEditPopup" position="center" :style="{ padding: '40rpx' }">
        <view class="relative bg-white rounded-2xl p-[40rpx] min-w-[600rpx] shadow-2xl">
            <!-- 关闭按钮 -->
            <view 
                class="absolute top-4 right-4 w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center cursor-pointer hover:bg-gray-200 transition-colors duration-200"
                @click="cancelEdit"
            >
                <IconFont name="close" size="16" color="#666"></IconFont>
            </view>
            
            <view class="flex flex-col items-center">
                <!-- 标题 -->
                <view class="flex items-center mb-6">
                    <view class="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-400 to-blue-500 flex items-center justify-center mr-3">
                        <IconFont name="edit" size="20" color="white" />
                    </view>
                    <text class="text-[44rpx] font-bold text-gray-800">编辑健康数据</text>
                </view>
                
                <!-- 当前数据展示 -->
                <view class="w-full mb-6 p-4 bg-gray-50 rounded-xl">
                    <text class="text-[36rpx] text-gray-600 mb-2 block">当前数值</text>
                    <text class="text-[40rpx] font-semibold text-gray-800">
                        {{ editingRecord?.subName }}：{{ editingRecord?.subRes }}
                    </text>
                </view>
                
                <!-- 输入框 -->
                <view class="w-full mb-6">
                    <text class="text-[36rpx] text-gray-700 mb-3 block">新数值</text>
                    <input 
                        v-model="editValue"
                        type="digit"
                        class="w-full p-4 border-2 border-gray-200 rounded-xl text-[40rpx] focus:border-blue-400 focus:outline-none transition-colors duration-200"
                        placeholder="请输入新的数值"
                    />
                </view>
                
                <!-- 按钮组 -->
                <view class="flex space-x-4 w-full">
                    <nut-button 
                        type="default" 
                        size="large" 
                        class="flex-1 h-12 rounded-xl"
                        @click="cancelEdit"
                    >
                        取消
                    </nut-button>
                    <nut-button 
                        type="primary" 
                        size="large" 
                        class="flex-1 h-12 rounded-xl"
                        @click="confirmEdit"
                    >
                        确认修改
                    </nut-button>
                </view>
            </view>
        </view>
    </nut-popup>
</template>

<script setup lang="ts">
import { IconFont } from '@nutui/icons-vue-taro'
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useHealthStore } from '@/store/modules/health'
import Care from '@/components/basic-comm/care.vue'
import { request } from '@/service/request'
import Taro from '@tarojs/taro'
import { useEmitter } from '@/hooks/common'

const healthStore = useHealthStore()
const emitter = useEmitter()

// 健康数据
const healthData = ref<any[]>([])
const loading = ref(false)

// 编辑相关状态
const showEditPopup = ref(false)
const editingRecord = ref<any>(null)
const editValue = ref('')

// 定义是否展开自定义区域的状态
const isCustomExpanded = ref(true)

// 切换自定义区域的展开状态
const toggleCustom = () => {
    isCustomExpanded.value = !isCustomExpanded.value
}

// 获取健康数据
const getHealthData = async () => {
    loading.value = true
    try {
        const { error, success } = await request.get('/health_records/health_basepro/healthBaseProjectInfo/list', {}, {
            useErrMsg: true
        })
        // res article
        if (!error && success) {
            healthData.value = (success as any).records || []
        }
    } catch (error) {
        // 获取健康数据失败
        Taro.showToast({
            title: '获取数据失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 根据项目名称获取图标
const getIconByName = (subName: string) => {
    const iconMap: Record<string, string> = {
        '血糖': 'droplet',
        '血氧': 'droplet',
        '血压': 'heart',
        '心率': 'heart',
        '体温': 'thermometer',
        '心电图': 'chart-line',
        '运动': 'running'
    }
    return iconMap[subName] || 'droplet'
}

// 根据数值判断健康状态
const getHealthStatus = (subName: string, subRes: string) => {
    const value = parseFloat(subRes)
    
    switch (subName) {
        case '血糖':
            if (value < 3.9) return { 
                status: '偏低', 
                color: 'bg-blue-100 text-blue-600',
                bgColor: 'bg-gradient-to-br from-blue-400 to-blue-500',
                dotColor: 'bg-blue-400'
            }
            if (value > 6.1) return { 
                status: '偏高', 
                color: 'bg-orange-100 text-orange-600',
                bgColor: 'bg-gradient-to-br from-orange-400 to-orange-500',
                dotColor: 'bg-orange-400'
            }
            return { 
                status: '正常', 
                color: 'bg-green-100 text-green-600',
                bgColor: 'bg-gradient-to-br from-green-400 to-green-500',
                dotColor: 'bg-green-400'
            }
        case '血氧':
            if (value < 95) return { 
                status: '偏低', 
                color: 'bg-red-100 text-red-600',
                bgColor: 'bg-gradient-to-br from-red-400 to-red-500',
                dotColor: 'bg-red-400'
            }
            return { 
                status: '正常', 
                color: 'bg-green-100 text-green-600',
                bgColor: 'bg-gradient-to-br from-green-400 to-green-500',
                dotColor: 'bg-green-400'
            }
        case '体温':
            if (value < 36.0 || value > 37.2) return { 
                status: '异常', 
                color: 'bg-red-100 text-red-600',
                bgColor: 'bg-gradient-to-br from-red-400 to-red-500',
                dotColor: 'bg-red-400'
            }
            return { 
                status: '正常', 
                color: 'bg-green-100 text-green-600',
                bgColor: 'bg-gradient-to-br from-green-400 to-green-500',
                dotColor: 'bg-green-400'
            }
        case '心率':
            if (value < 60 || value > 100) return { 
                status: '异常', 
                color: 'bg-orange-100 text-orange-600',
                bgColor: 'bg-gradient-to-br from-orange-400 to-orange-500',
                dotColor: 'bg-orange-400'
            }
            return { 
                status: '正常', 
                color: 'bg-green-100 text-green-600',
                bgColor: 'bg-gradient-to-br from-green-400 to-green-500',
                dotColor: 'bg-green-400'
            }
        default:
            return { 
                status: '正常', 
                color: 'bg-green-100 text-green-600',
                bgColor: 'bg-gradient-to-br from-green-400 to-green-500',
                dotColor: 'bg-green-400'
            }
    }
}

// 格式化显示值
const formatDisplayValue = (subName: string, subRes: string, updateTime?: string) => {
    const timeStr = updateTime ? ` (${updateTime})` : ''
    switch (subName) {
        case '血糖':
            return `血糖数值：${subRes} mmol/L${timeStr}`
        case '血氧':
            return `血氧饱和度：${subRes}%${timeStr}`
        case '血压':
            return `血压：${subRes} mmHg${timeStr}`
        case '心率':
            return `心率：${subRes} 次/分${timeStr}`
        case '体温':
            return `体温度数：${subRes}°C${timeStr}`
        case '心电图':
            return `心电数值：${subRes}${timeStr}`
        case '运动':
            return `运动分数：${subRes}${timeStr}`
        default:
            return `${subName}：${subRes}${timeStr}`
    }
}



// 编辑健康记录
const editHealthRecord = (record: any) => {
    editingRecord.value = record
    editValue.value = record.subRes
    showEditPopup.value = true
}

// 确认编辑
const confirmEdit = async () => {
    if (!editValue.value.trim()) {
        Taro.showToast({
            title: '请输入数值',
            icon: 'none'
        })
        return
    }

    try {
        const { error, success } = await request.post('/health_records/health_basepro/healthBaseProjectInfo/edit', {
            id: editingRecord.value.id,
            subRes: editValue.value
        }, {
            useErrMsg: true
        })

        if (!error && success) {
            Taro.showToast({
                title: '修改成功',
                icon: 'success'
            })
            
            // 关闭弹窗
            showEditPopup.value = false
            editingRecord.value = null
            editValue.value = ''
            
            // 重新获取数据
            getHealthData()
        } else {
            Taro.showToast({
                title: '修改失败',
                icon: 'none'
            })
        }
    } catch (error) {
        // 修改失败
        Taro.showToast({
            title: '修改失败',
            icon: 'none'
        })
    }
}

// 取消编辑
const cancelEdit = () => {
    showEditPopup.value = false
    editingRecord.value = null
    editValue.value = ''
}

// 删除健康记录
const deleteHealthRecord = async (id: string) => {
    try {
        // 显示确认对话框
        const result = await Taro.showModal({
            title: '确认删除',
            content: '确定要删除这条健康记录吗？',
            confirmText: '删除',
            cancelText: '取消',
            confirmColor: '#ef4444'
        })
        
        if (result.confirm) {
            // 调用删除接口
            const { error, success } = await request.delete(`/health_records/health_basepro/healthBaseProjectInfo/delete?id=${id}`, {}, {
                useErrMsg: true
            })
            
            if (!error && success) {
                Taro.showToast({
                    title: '删除成功',
                    icon: 'success'
                })
                
                // 重新获取数据
                getHealthData()
            } else {
                Taro.showToast({
                    title: '删除失败',
                    icon: 'none'
                })
            }
        }
    } catch (error) {
        // 删除失败
        Taro.showToast({
            title: '删除失败',
            icon: 'none'
        })
    }
}

// 页面加载时获取数据
onMounted(() => {
    getHealthData()
    
    // 监听刷新健康数据事件
    emitter.$on('refreshHealthData', () => {
        getHealthData()
    })
})

// 组件卸载时清理事件监听
onUnmounted(() => {
    emitter.$off('refreshHealthData')
})
</script>
